package cn.edu.sjtu.literature.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.edu.sjtu.literature.web.controller.Controller;
import cn.edu.sjtu.literature.web.controller.ControllerFactory;
import cn.edu.sjtu.literature.web.controller.DefaultControllerFactory;
import cn.edu.sjtu.literature.web.view.RedirectView;
import cn.edu.sjtu.literature.web.view.View;

public class ServletDispatcher extends HttpServlet {

	private static final long serialVersionUID = -9109907952510746333L;
	
	private static final Log LOG = LogFactory.getLog(ServletDispatcher.class);
	
	private ControllerFactory controllerFactory = DefaultControllerFactory.getInstance();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doAction(req, resp);
	}
	
	protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		LOG.debug("servlet path: " + req.getServletPath());
		LOG.debug("request uri: " + req.getRequestURI());
		String realServletPath = req.getRequestURI().replaceFirst(req.getContextPath(), "").replaceFirst(req.getServletPath(), "");
		LOG.debug("real servlet path: " + realServletPath);
		Controller controller = controllerFactory.getController(realServletPath);
		if (controller == null) {
			LOG.debug("controller not found");
			resp.sendError(HttpServletResponse.SC_NOT_FOUND, "page not found");
		} else {
			LOG.debug("controller found: " + controller);
			View view = controller.doAction(req, resp);
			LOG.debug("do action successfully, return view: " + view);
			if (view == null) return;
			if (view instanceof RedirectView) {
				LOG.debug("send redirect to: " + view.getUri());
				resp.sendRedirect(view.getUri());
			} else {
				LOG.debug("forward to: " + view.getUri());
				req.getRequestDispatcher(view.getUri()).forward(req, resp);
			}
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doAction(req, resp);
	}

}
